<template>
	<base-page title="补贴设置" backgroundColor="white">
		<view class="flex-1 m-16">
			<view class="p-16 radius-12 bg-white mb-16" style="box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.20);">
				<view class="flex item-center mb-8" @click="onSelect(1)">
					<image v-if="subsidyState===1" class="w-16 h-16 mr-8" src="@/static/svg/radio-selected.svg"></image>
					<image v-else class="w-16 h-16 mr-8" src="@/static/svg/radio-default.svg"></image>
					<text class="text-bold">自动按价格比例分摊</text>
				</view>
				<view class="ml-24 flex-col fs-12 text-color-hint">
					<text class="mb-32">系统自动按补贴金额比例分摊</text>
					<text>如A商品30元，B商品50 元，活动价格60元，即补贴金额20元则A补贴金额=30/80*20=7.5元</text>
				</view>
			</view>
			<view  v-if="!isZeroState" class="p-16 radius-12 bg-white mb-16" style="box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.20);">
				<view class="flex justify-between item-center mb-8">
					<view class="flex item-center" @click="onSelect(2)">
						<image v-if="subsidyState===2" class="w-16 h-16 mr-8" src="@/static/svg/radio-selected.svg"></image>
						<image v-else class="w-16 h-16 mr-8" src="@/static/svg/radio-default.svg"></image>
						<text class="text-bold">手动设置</text>
					</view>
					<view>
						<text>单订单补贴金额:</text>
						<text class="color-primary">{{numberFormat(subsidyTotal)}}</text>
					</view>
				</view>
				<view class="ml-24 mb-8 flex-col fs-12 text-color-hint">
					<view>单订单补贴金额=商品价格总和-活动价+单个红包金额</view>
					<view>填写的补贴金额总和须等于单订单补贴金额</view>
				</view>
				<view>
					<view class="bg-default h-44 flex item-center px-12 flex" style="border-radius:8px 8px 0px 0px;">
						<text class="flex-shrink mr-12" style="width:45%;">商品名称</text>
						<text class="flex-1 mr-12">商品价格</text>
						<text class="flex-1">补贴金额</text>
					</view>
					<view v-for="(goods,i) in activeGoodsSubsidy" :key="i" class="h-44 flex item-center px-12">
						<text class="flex-shrink mr-12 text-cut" style="width:45%;">{{goods.goodsName}}</text>
						<text class="flex-1 mr-12">{{numberFormat(goods.goodsPrice)}}</text>
						<view class="flex-1">
							<input
								type="digit"
								:maxlength="8"
								:value="numberFormat(goods.subsidyAmt)"
								@blur="goods.subsidyAmt=numberFormat($event.detail.value)"
							/>
						</view>
					</view>
				</view>
			</view>
		</view>
		<template #footer>
			<view class="m-12 flex-shrink">
				<button class="flex center radius-8 bg-primary h-46 fs-16 text-white font-normal leading-22" @click="submit">确认</button>
			</view>
		</template>
	</base-page>
</template>


<script setup name="SubsidySetting">
	/**
	 * 补贴设置
	 */
	import { onLoad } from '@dcloudio/uni-app'
	import {
		computed,
		ref,
		toRaw,
		getCurrentInstance,
	} from 'vue'
	import { floorNumber, numberFormat } from '@/utils/index.js'

	const instance = getCurrentInstance()
	
	// 活动商品列表 (团购)
	const activeGoods = ref([])
	// 补贴设置(0-未设置,1-自动按比例分摊,2-手动设置)
	const subsidyState = ref(0)
	// 活动商品补贴列表
	const activeGoodsSubsidy = ref([])
	// 活动价格
	const activePrice = ref(0)
	// 单个红包金额
	const activeRedPacket = ref(0)
	const isZeroState = ref(false)
	// 补贴金额
	const subsidyTotal = computed(() => {
		// 套餐内所有商品价格-活动价格+单个红包金额=单订单总补贴金额
		let totalGoodsPrice = 0
		for (let i = 0; i < activeGoods.value.length; i++) {
			const goods = activeGoods.value[i]
			totalGoodsPrice += goods.goodsPrice * goods.goodsNum
		}
		
		const val = +floorNumber(totalGoodsPrice - activePrice.value + activeRedPacket.value + commission.value)
		console.log('佣金', commission.value, '补贴金额：', val)
		return val < 0 ? 0 : val
	})
	// 分销开启状态(1-关闭，2-开启)
	const agentState = ref('')
	// 默认佣金类型：0-无，1-佣金，2-佣金比例
	const defaultCommissionType = ref('')
	// 分销佣金金额
	const commissionAmt = ref(0)
	// 分销佣金比例
	const commissionRate = ref('')
	// 佣金
	const commission = computed(() => {
		console.log('佣金', agentState.value, defaultCommissionType.value, commissionAmt.value, commissionRate.value)
		if (agentState.value === 2) {
			if (defaultCommissionType.value === 1) {
				return commissionAmt.value
			} else if (defaultCommissionType.value === 2) {
				return +floorNumber((activePrice.value * commissionRate.value) / 100)
			} else {
				return 0
			}
		} else {
			return 0
		}
	})
	
	const onSelect = (type) => {
		subsidyState.value = type
	}
	
	const submit = () => {
		if (subsidyState.value === 0) {
			uni.showToast({
				title: '请选择补贴方式',
				icon: 'none'
			})
			return
		}
		if (subsidyState.value === 2) {
			let totalSubsidyAmt = 0
			for (var i = 0; i < activeGoodsSubsidy.value.length; i++) {
				const item = activeGoodsSubsidy.value[i]
				totalSubsidyAmt += +item.subsidyAmt || 0
				if (+item.subsidyAmt > item.goodsPrice) {
					uni.showToast({
						icon: 'none',
						title: '补贴金额不能超过商品价格'
					})
					return
				}
			}
			console.log('补贴总金额', totalSubsidyAmt, subsidyTotal.value)
			if (+subsidyTotal.value > 0 && totalSubsidyAmt !== +subsidyTotal.value) {
				uni.showToast({
					title: `总补贴金额需等于${subsidyTotal.value}元`,
					icon: 'none'
				})
				return
			}
		}
		const eventChannel = instance.ctx.getOpenerEventChannel()
		eventChannel.emit('onSubsidyChange', {
			subsidyState: subsidyState.value,
			activeGoodsSubsidy: activeGoodsSubsidy.value,
		})
		uni.navigateBack()
	}

	onLoad(() => {
		const eventChannel = instance.ctx.getOpenerEventChannel()
		eventChannel.on('acceptDataFromOpenerPage', (data) => {
			agentState.value = toRaw(data.agentState)
			defaultCommissionType.value = toRaw(data.defaultCommissionType)
			commissionAmt.value = toRaw(data.commissionAmt)
			commissionRate.value = toRaw(data.commissionRate)
			subsidyState.value = toRaw(data.subsidyState)
			activeGoods.value = toRaw(data.activeGoods || [])
			activeGoodsSubsidy.value = toRaw(data.activeGoodsSubsidy || [])
			isZeroState.value = data.isZeroState
			if (activeGoodsSubsidy.value.length === 0) {
				for (let i = 0; i < activeGoods.value.length; i++) {
					const goods = activeGoods.value[i]
					console.log('拆分', goods, goods.goodsNum)
					for (let j = 0; j < goods.goodsNum; j++) {
						activeGoodsSubsidy.value.push({
							...goods,
							goodsNum: 1,
							subsidyAmt: ''
						})
					}
				}
				console.log('未设置补贴', activeGoodsSubsidy.value)
			} else {
				const newList = []
				for (let i = 0; i < activeGoods.value.length; i++) {
					const goods = activeGoods.value[i]
					// 相同的商品已有补贴设置
					const oldGoodsSubsidy = activeGoodsSubsidy.value
						.filter(it => {
							// 多商户券
							if (it.mulState === 2) {
								return it.goodsId == goods.goodsId && it.mulState === goods.mulState && it.goodsName === goods.goodsName && it.goodsPrice == goods.goodsPrice && it.details == goods.details
							} else {
								return it.goodsId == goods.goodsId && it.mulState === goods.mulState
							}
						}) || []
					// console.log('原来的商品补贴设置', oldGoodsSubsidy)
					if (oldGoodsSubsidy.length) {
						// 商品数量不变，保留原来的补贴设置
						if(goods.goodsNum === oldGoodsSubsidy.length) {
							for (let j = 0; j < oldGoodsSubsidy.length; j++) {
								newList.push({
									...goods,
									goodsNum: 1,
									subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
								})
							}
						} else if(goods.goodsNum < oldGoodsSubsidy.length) {
							// 数量有删减
							// 按值大小重新排序，优先保留有值的
							oldGoodsSubsidy.sort((a, b) => b.subsidyAmt - a.subsidyAmt)
							// console.log('排序后的', oldGoodsSubsidy)
							for (let j = 0; j < goods.goodsNum; j++) {
								newList.push({
									...goods,
									goodsNum: 1,
									subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
								})
							}
						} else {
							// 数量有增加
							// 1.先保留原来的
							for (let j = 0; j < oldGoodsSubsidy.length; j++) {
								newList.push({
									...goods,
									goodsNum: 1,
									subsidyAmt: oldGoodsSubsidy[j].subsidyAmt
								})
							}
							// 2.再新增的补贴状态初始化
							for (let j = 0; j < goods.goodsNum - oldGoodsSubsidy.length; j++) {
								newList.push({
									...goods,
									goodsNum: 1,
									subsidyAmt: ''
								})
							}
						}
					} else {
						// 新增商品或未设置补贴，重新生成初始补贴状态
						for (let j = 0; j < goods.goodsNum; j++) {
							newList.push({
								...goods,
								goodsNum: 1,
								subsidyAmt: ''
							})
						}
					}
				}
				
				activeGoodsSubsidy.value = newList
				console.log('已有设置补贴', activeGoodsSubsidy.value, '新的补贴设置', newList)
			}
			activePrice.value = data.activePrice
			activeRedPacket.value = data.activeRedPacket
			console.log('传值', data)
		})
	})
</script>
